<?php


namespace PKApp\Form;

use PKApp\Form\Classes\FormService;
use PKApp\Model\Classes\TraitModel;
use PKApp\Site\Classes\SiteController;
use PKCommon\MailTrait;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

class PutFormData extends SiteController
{
    use MailTrait, TraitModel;

    protected $id_form, $params_form, $language;

    public function Main()
    {
        $this->GuestIP_isExpire(request()->module(), 60) ?: $this->noticeByJson('Err_postHigh');
        $this->_checkParams();
        if ($this->_serviceForm()->is_singleSubmit) {
            $this->_singleSubmit();
        }
        if ($this->_serviceForm()->is_insertDB) {
            $this->_insetDB();
        }
        if ($this->_serviceForm()->is_sendMail) {
            $this->_sendEmail();
        }
        $this->json([]);
    }

    private function _singleSubmit()
    {
        $restrictField = $this->_serviceForm()->restrictField;
        !empty($restrictField) ?: $this->noticeByJson('Empty_restrictField');
        $restrict_params = ['siteId' => $this->getSiteEntity()->Id];
        $list_restrict = explode(',', $restrictField);
        foreach ($list_restrict as $item) {
            $restrict_params[$item] = $this->checkPostFieldIsEmpty($item,'Empty_restrictField');
        }
        $is_exists = $this->_serviceForm()->isExistsData(
            $this->_uuid(), request()->GuestIP(), $restrict_params);
        boolval($is_exists) == false ?: $this->noticeByJson('Exists_data');
    }

    private function _checkParams()
    {
        $this->id_form = $this->checkPostFieldIsEmpty('formId', 'Model_IdEmpty', 'model');
        request()->language(request()->post('language'));
        Numbers::IsId($this->id_form) ?: $this->noticeByJson('Model_IdEmpty', 'model');
        $this->modelOfToInsertData()->Get(request()->post(), $this->id_form);
        $this->params_form = $this->modelOfToInsertData()->listField_data;
    }

    private function _serviceForm(): FormService
    {
        static $cls;
        !empty($cls) ?: $cls = new FormService($this->id_form);
        return $cls;
    }

    private function _uuid(): string
    {
        return language('Guest') . $this->checkPostFieldIsEmpty('uuid', 'Err_uuid');
    }

    /**
     * 将提交的数据录入到数据库中
     */
    private function _insetDB()
    {
        // 入库数据
        $id_user = Numbers::To(request()->cookie('userId'));
        $ip_user = request()->GuestIP();
        // TODO: 前台会员提交
        $params_db = array_merge($this->params_form, [
            'siteId' => $this->getSiteEntity()->Id,
            'createIP' => $ip_user,
            'createUserId' => $id_user,
            'createUserName' => $this->_uuid(),
            'createTime' => TIMESTAMP,
            'status' => 'await',
            'isDelete' => 0,
        ]);
        $this->_serviceForm()->InsertDBByUser($params_db);
    }

    /**
     * 发送邮件
     */
    private function _sendEmail()
    {
        $html = '';
        $list_option = $this->modelOfToInsertData()->listField_option_data;
        foreach ($this->params_form as $field => $value) {
            if (Arrays::Is($list_option) && array_key_exists($field, $list_option)) {
                $fieldList_option = $list_option[$field];
                $value = Arrays::GetKey($value, $fieldList_option);
            }
            $html .= $this->modelOfToInsertData()->listField_name[$field] . ':' . htmlspecialchars_decode($value) . ".\r";
        }
        $this->sendMail($this->_serviceForm()->to_mailAddress, $html);
    }

}